﻿using System;
using System.Diagnostics;
using System.Security;
using System.Text;
using System.Threading;
using System.Web;

namespace Jsdl.Service
{
    public abstract class AuthenticatedJsdlServicesHandlerBase : JsdlServicesHandlerBase
	{
		public abstract bool CheckUser(string username, string password);
		public abstract bool IsUserInRole(string username, string role);

		public override void ProcessRequest(HttpContext context)
		{
			try
			{
				var authorization = context.Request.Headers["Authorization"];
				if (authorization != null && authorization.StartsWith("Basic "))
				{
					authorization = authorization.Substring(6);
					authorization = Encoding.UTF8.GetString(Convert.FromBase64String(authorization));

					var index = authorization.IndexOf(':');
					if (index != -1)
					{
						var username = authorization.Substring(0, index);
						var password = authorization.Substring(index + 1);

						if (CheckUser(username, password))
						{
							var principal = new JsdlPrincipal(this, username);
							HttpContext.Current.User = principal;
							Thread.CurrentPrincipal = principal;
						}
						else
							throw new SecurityException("wrong_username_or_password");
					}
				}
			}
			catch (SecurityException ex)
			{
				WriteException(context, 401, "security", ex.Message, "");
				return;
			}
			catch (Exception ex)
			{
				if (Debugger.IsAttached)
					Debugger.Break();

				WriteException(context, 401, "security", ex.GetType().Name, "");
				return;
			}

			base.ProcessRequest(context);
		}
	}
}